package com.macro.cloud.userservice.service.impl;

import com.macro.cloud.userservice.result.User;
import com.macro.cloud.userservice.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    private List<User> userList;
    @Override
    public void create(User user) {
        userList.add(user);
    }
//https://github.com/macrozheng/springcloud-learning/blob/master/user-service/src/main/java/com/macro/cloud/service/impl/UserServiceImpl.java
    @Override
    public User getUser(Long id) {
        List<User> users = userList.stream().filter(user -> user.getId().equals(id)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(users)){
            return users.get(0);
        }
        return null;
    }

    @Override
    public List<User> getUserByIds(List<Long> ids) {
        return userList.stream().filter(user -> ids.contains(user.getId())).collect(Collectors.toList());

    }

    @Override
    public User getUserByName(String username) {
        List<User> users = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(users)){
            return users.get(0);
        }
        return null;
    }

    @Override
    public void update(User user) {
        userList.stream().filter(userItem -> userItem.getId().equals(user.getId()))
                    .forEach(userItem -> {
                        userItem.setUsername(user.getUsername());
                        userItem.setPassword(user.getPassword());
                    });
    }

    @Override
    public void delete(Long id) {
        User user = getUser(id);
        if(user != null){
            userList.remove(user);
        }

    }

    @PostConstruct
    public void initData(){
        userList = new ArrayList<User>();
        userList.add(new User(1L, "macro", "123456"));
        userList.add(new User(2L, "andy", "123456"));
        userList.add(new User(3L, "mark", "123456"));
    }

}
